package angry.courses.beans;

import javax.ejb.Stateless;
import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import java.util.List;
import java.util.ArrayList;

import angry.courses.entities.CourseEntity;

@Stateless
public class CourseDAOBean implements CourseDAO {
	@PersistenceContext
	private EntityManager em;
	
	public CourseEntity retrieve(String name) {
		CourseEntity course = null;
		try {
			Query query = em.createNamedQuery("retrieveCourse");
			query.setParameter("name", name);
			course = (CourseEntity) query.getSingleResult();
		} catch(Exception e) {
			course = null;
		}
		return course;
	}
	
	public CourseEntity retrieve(int cid) {
		CourseEntity course = null;
		try {
			Query query = em.createNamedQuery("retrieveCourseByCid");
			query.setParameter("cid", cid);
			course = (CourseEntity) query.getSingleResult();
		} catch(Exception e) {
			course = null;
		}
		return course;
	}
	
	public List<CourseEntity> getAllForSemester(int sem) {
		List<CourseEntity> courses = null;
		try {
			Query query = em.createNamedQuery("retrieveCoursesForSemester");
			query.setParameter("semester", sem);
			courses = (List<CourseEntity>) query.getResultList();
		} catch(Exception e) {
			courses = new ArrayList<CourseEntity>();
		}
		return courses;
	}
	
	public List<CourseEntity> getForYearAndSemester(int year, int semester) {
		List<CourseEntity> courses = null;
		try {
			Query query = em.createNamedQuery("retrieveCoursesForYearAndSemester");
			query.setParameter("year", year);
			query.setParameter("semester", semester);
			courses = (List<CourseEntity>) query.getResultList();
		} catch(Exception e) {
			courses = new ArrayList<CourseEntity>();
		}
		return courses;
	}
	
	public void create(CourseEntity course) {
		em.persist(course);
	}
	
	public void remove(CourseEntity course) {
		CourseEntity existing = em.find(CourseEntity.class, course.getID());
		em.remove(existing);
	}
}
